package com.dankegongyu.lib.http.interceptor;

import android.text.TextUtils;

import com.dankegongyu.lib.http.model.DKHttpHeaders;

import java.io.IOException;
import java.util.Map;

import io.reactivex.annotations.NonNull;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author wupuquan
 * @version 1.0
 * @since 2019/3/22 11:55
 */
public class DKHeaderInterceptor implements DKBaseInterceptor {

    private DKHttpHeaders mHeaders;

    public DKHeaderInterceptor(DKHttpHeaders headers) {
        this.mHeaders = headers;
    }

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        if (mHeaders == null || mHeaders.isEmpty()) {
            return chain.proceed(builder.build());
        }
        try {
            for (Map.Entry<String, String> entry : mHeaders.getHeaders().entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (!TextUtils.isEmpty(key) && value != null) {
                    builder.header(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chain.proceed(builder.build());
    }
}
